/*
 * 上海远境文化传媒有限公司 版权所有
 */
package helper;


import org.apache.commons.lang3.time.DateUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import play.Logger;
import util.DateHelper;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * 日期时间转换类.
 */
public class DateTimeParser {

    public static final String DEFAULT_DATE_FORMAT_PATTERN     = "yyyy-MM-dd";
    public static final String DEFAULT_DATETIME_FORMAT_PATTERN = "yyyy-MM-dd HH:mm:ss";
    public static final String SHORT_DATETIME_FORMAT_PATTERN   = "yyyy-MM-dd HH:mm";
    public static final String SHORT_TIME_FORMAT_PATTERN       = "HH:mm";

    public static Date parse(String date) {
        return parse(date, DEFAULT_DATE_FORMAT_PATTERN);
    }

    public static Date date(String date) {
        return parse(date, DEFAULT_DATE_FORMAT_PATTERN);
    }

    public static Date dt(String date) {
        return parse(date, DEFAULT_DATETIME_FORMAT_PATTERN);
    }

    public static Date sdt(String date) {
        return parse(date, SHORT_DATETIME_FORMAT_PATTERN);
    }

    public static Date shortTime(String date) {
        return parse(date, SHORT_TIME_FORMAT_PATTERN);
    }


    public static Date parse(String date, String formatPattern) {
        if (date == null) {
            return null;
        }
        SimpleDateFormat formatDate = new SimpleDateFormat(formatPattern);
        try {
            return formatDate.parse(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 传入 2015:12, 返回这个周的开始时间和结束时间.
     * @param yearWeek 格式yyyy:W
     * @return  Pair<begin, end>值 begin是周一, end是周日
     */
    public static Pair<LocalDate, LocalDate> getWeekBeginAndEndDate(String yearWeek) {
        try {
            Date date = DateUtils.parseDate(yearWeek, "yyyy:w");

            LocalDate localDate = DateHelper.afterDays(date, 2).toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

            Logger.info("LOG03850: day=%s, week=%s", localDate.toString(), localDate.format(DateTimeFormatter.ofPattern("yyyy-w")));

            return new ImmutablePair<>(localDate.with(DayOfWeek.MONDAY),
                    localDate.with(DayOfWeek.SUNDAY));
        } catch (ParseException e) {
            Logger.warn(e, "LOG03830: 格式异常" + yearWeek);
        }
        return null;
    }

    /**
     * 转换Date为LocalDateTime
     */
    public static LocalDateTime convertToLocalDateTime(Date date) {
        if (date == null) {
            return null;
        }
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(date.toInstant(), zone);
    }

}
